/*
 * @Description:
 * @Author: Zzt
 * @Date: 2022-11-07 19:06:35
 * @LastEditTime: 2023-01-29 14:45:07
 */

import { createContext, useReducer, useEffect, useContext } from 'react';
import {
  SET_REPORT_LIST,
  ADD_REPORT_LIST,
  DELETE_REPORT_LIST,
  SET_SELECT_KEY,
  EDIT_REPORT_LIST,
  SET_SELECT_FOND,
  SET_SELECT_AT,
  SET_SELECT_LEVEL
} from '../constants';
import { ReportTemplateReducer } from '../reducers/ReportTemplateReducer';
import { message, Modal } from 'antd';
import {
  addReportTemp,
  editReportTemp,
  fetchReportListByPage,
  deleteReportList,
  designBaseurl,
  previewBaseurl
} from '@/api/report';

const initialState = {
  // 当前选中的项目
  selectFond: {},
  selectAT: {},
  selectLevel: {},
  // 选中的表格条目
  selectItems: [],

  reportList: [],

  // -------- 字典 --------º
  // 数据来源
  levelTempTypeList: [
    { id: 1, name: '封面' },
    { id: 2, name: '脊背' },
    { id: 3, name: '备考表' },
    { id: 4, name: '盒内目录' }
  ],
  // 数据来源
  dataMappingList: [
    { id: 1, name: '一对一' },
    { id: 2, name: '一对多' }
  ]
};

const ReportTemplateContext = createContext();

const ReportTemplateContextProvider = (props) => {
  const [state, dispatch] = useReducer(ReportTemplateReducer, initialState);
  const actions = {
    /**
     * @description: 打开新增全宗弹窗
     */
    setSelectFond(data) {
      dispatch({ type: SET_SELECT_FOND, data });
    },

    /**
     * @description: 设置选中的档案类型
     */
    setSelectAT(data) {
      dispatch({ type: SET_SELECT_AT, data });
    },

    /**
     * @description: 设置选中的层级
     */
    setSelectLevel(data) {
      dispatch({ type: SET_SELECT_LEVEL, data });
    },

    setSelectKey(data) {
      dispatch({ type: SET_SELECT_KEY, data });
    },

    getReportTempList(data) {
      return new Promise((resolve, reject) => {
        fetchReportListByPage(data)
          .then((res) => {
            const { data } = res;
            dispatch({ type: SET_REPORT_LIST, data: data.results });
            resolve(data);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },

    /* 增加报表模板列表 */
    addReportTempFunc(query) {
      return new Promise((resolve, reject) => {
        addReportTemp(query)
          .then((res) => {
            const { data } = res;
            dispatch({ type: ADD_REPORT_LIST, data });
            resolve(data);
          })
          .catch((err) => reject(err));
      });
    },

    /* 编辑报表模板列表 */
    editReportTempFunc(query) {
      return new Promise((resolve, reject) => {
        editReportTemp(query)
          .then((res) => {
            const { data } = res;
            dispatch({ type: EDIT_REPORT_LIST, data, id: data.id });
            resolve(data);
          })
          .catch((err) => reject(err));
      });
    },

    /* 删除报表模板列表 */
    delReportTemplateFunc(id, title = '确认删除此报表模板吗？') {
      Modal.confirm({
        title: '删除提醒',
        content: title,
        onOk() {
          const ids = id instanceof Array ? id.join(',') : id;
          deleteReportList(ids).then((res) => {
            message.success('删除成功');
            const { data } = res;
            console.log('dataddd', data);
            dispatch({ type: DELETE_REPORT_LIST, ids: data });
          });
        },
        onCancel() {
          console.log('Cancel');
        }
      });
    },

    /**
     * @description: 打开新页面
     * @param {string} url 页面url
     */
    openReportTemp: (url) => {
      window.open(url);
    },

    /**
     * @description: 打开模板设计页面
     * @param {Key} id 关联id
     */
    openDesign: (id) => {
      actions.openReportTemp(`${designBaseurl}?${id}`);
    },

    /**
     * @description: 打开预览模板页面
     * @param {Key} id 链接参数
     */
    openPreview: (id) => {
      // const propsArr = Object.entries(urlProps).map(([key, val]) => `${key}=${val}`);
      // console.log({ propsArr });
      actions.openReportTemp(`${previewBaseurl}${id}`);
    }
  };

  const filters = {
    typeFilter(id) {
      return state.levelTempTypeList.find((item) => item.id === id)?.name || '-';
    },
    dataMappingFilter(id) {
      return state.dataMappingList.find((item) => item.id === id)?.name || '-';
    }
  };

  useEffect(() => {}, []);
  return (
    <ReportTemplateContext.Provider value={{ ...state, ...actions, ...filters }}>
      {props.children}
    </ReportTemplateContext.Provider>
  );
};

export const useReportTemplateContext = () => {
  return useContext(ReportTemplateContext);
};

export { ReportTemplateContext, ReportTemplateContextProvider };
